package com.example.service.util.service;

import com.example.service.util.utils.MailTemplateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @Author juzipi
 * @Date 2021/7/30 8:36
 * @Info
 */
@Component
public class MailService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MailProperties mailProperties;

    @Autowired
    private JavaMailSender javaMailSender;


    /**
     * 发送html邮件
     * @param email 邮箱
     * @param subject 主题
     * @param template 模板
     * @return
     */
    public Boolean sendRemindEmail(String email,String subject,String template){
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(mailProperties.getUsername());
            mimeMessageHelper.setTo(email);//接收方
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(template,true);
            javaMailSender.send(mimeMessage);
            logger.info("邮件发送成功 ------------> "+email);
            return true;
        } catch (MessagingException e) {
            logger.error("发送邮件失败 ------------> "+e.getMessage());
            e.printStackTrace();
            return false;
        }
    }


}
